<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getloginlogdata, getLoginlogdatalike, delLoginlog } from '../../api/api'
let total = ref(0)
let page = ref(1)
let pageSize = ref(8)
onMounted(() => {
  getloginlog()
})
// 定义的头部输入框的数据
let topdata = ref({
  username: ''
})
// 表格数据
let tableData = ref([])
// 获取管理员管理的数据
async function getloginlog() {
  try {
    let data = await getloginlogdata(page.value, pageSize.value)
    if (data.code == 200) {
      total.value = data.total
      tableData.value = data.rows
    }
  } catch (error) {
    console.log(error);
  }
}
// 渲染状态的显示
let switchFlag = (flag) => {
  return flag == 0 ? true : false;
}
// 删除
let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
  dianjiid.value = val.loginId
  dialogVisible.value = true
}
async function yesdel() {
  dialogVisible.value = false
  try {
      let res = await delLoginlog(dianjiid.value);
      if (res.code == 200) {
          ElMessage.success(res.msg)
          getloginlog()
      }
  } catch (error) {
      console.log(error);
  }
}
// 遮罩层
let dialogFormVisible = ref(false)
let changeType = ref("")

//  传递参数
let formlist = reactive({})
function add() {
  // Object.assign(formlist, {
  //     username: "",
  //     nickname: "",
  //     password: "",
  //     phone: "",
  //     email: "",
  //     gender: 0,
  //     area: "",
  //     contry: "",
  //     addresszhou: "",
  //     account: "",
  //     userLevel: 1,
  //     type: "新增",
  //     roleName: [],
  //     phoneAreaCode: ''
  // })
  // console.log(formlist);
  // dialogFormVisible.value = true
  console.log("新增操作");
  changeType.value = 'add'
}
function edit(index, row) {
  // let arr = []
  // if (row.roles !== null) {
  //     row.roles.forEach(item => {
  //         arr.push(item.roleId)
  //     })
  // }
  // Object.assign(formlist, {
  //     userId: row.userId,
  //     nickname: row.nickname,
  //     email: row.email,
  //     phone: row.phone,
  //     gender: row.gender,
  //     area: row.area,
  //     contry: "",
  //     addresszhou: "",
  //     account: row.address,
  //     userLevel: row.userLevel,
  //     type: "修改",
  //     roleName: arr,
  //     roleoption: row.roles,
  //     phoneAreaCode: row.phoneAreaCode
  // })
  // console.log(formlist);
  changeType.value = "update"
  dialogFormVisible.value = true
}
function closechange() {
  dialogFormVisible.value = false
  getloginlog()
}
let isSearching = ref(false);
async function adminlike() {
  console.log("模糊查询操作");
  isSearching.value = true;
  console.log(topdata.value);
  let { username } = topdata.value
  if(topdata.value.username == ''){
    return;
  }
  try {
    let res = await getLoginlogdatalike(username, page.value, pageSize.value)
    console.log(res);
    if (res.code == 200) {
      tableData.value = res.rows
      if (res.rows.length == 0) {
        return;
      }
      total.value = res.total
    }
  } catch (error) {
    console.log(error);
  }
}
function cancel() {
  console.log("重置操作");
  isSearching.value = false;
  topdata.value = {
    username: ''
  }
  page.value = 1
  getloginlog()
}
async function getCurrentPage(e) {
  console.log("获取当前页", e);
  page.value = e
  if (isSearching.value) {
    try {
      await adminlike()
    } catch (error) {
      console.log(error);
    }
  } else {
    getloginlog()
  }
}
function detailfun(row) {
  // let arr = []
  // if (row.roles !== null) {
  //     row.roles.forEach(item => {
  //         arr.push(item.roleId)
  //     })
  // }
  // Object.assign(formlist, {
  //     username: row.username,
  //     userId: row.userId,
  //     nickname: row.nickname,
  //     email: row.email,
  //     phone: row.phone,
  //     gender: row.gender,
  //     area: row.area,
  //     contry: "",
  //     addresszhou: "",
  //     account: row.address,
  //     userLevel: row.userLevel,
  //     type: "修改",
  //     roleName: arr,
  //     roleoption: row.role,
  //     roles: row.roles,
  //     phoneAreaCode: row.phoneAreaCode
  // })
  // data.data.forEach(country => {
  //     if (country.state_code == row.area.split("/")[0]) {
  //         formlist.contry = country.name;
  //         country.states.forEach(st => {
  //             if (st.state_code == row.area.split("/")[1]) {
  //                 formlist.addresszhou = st.name;
  //             }
  //         })
  //     }
  // });
  // console.log(formlist);
  // changeType.value = "detail"
  // dialogFormVisibleDetail.value = true
}
const hasPermission = (permission) => {
  const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
  if (permissions[0] === '*:*:*') {
    return true;
  }
  return permissions.includes(permission);
};
</script>

<template>
  <div class="administrator">
    <div class="administratorbas">
      <div class="top">
        <span>login Log</span>
      </div>
      <div class="cont">
        <div class="one">
          <!-- 输入操作用户名 -->
          <div class="select">
            <el-input v-model="topdata.username" class="inp" style="width: 240px;"
              placeholder="Enter user operate username">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <search />
                </el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary" @click="adminlike">query</el-button>
          <el-button type="primary" @click="cancel">reset</el-button>
        </div>
        <!-- <div class="exp">
          <div class="export-excel">
            <el-button style="width: 160px" type="primary" @click="add()">
              <el-icon>
                <FolderAdd />
              </el-icon>Add Administrator
            </el-button>
          </div>
        </div> -->
        <div class="tab">
          <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true" v-if="hasPermission('system:login:query')">
            <el-table-column width="55">
            </el-table-column>
            <el-table-column property="username" label="username"/>
            <el-table-column property="userType" label="userType" width="150">
              <template #default="scope">
                <span>{{ {
                  0: 'SuperAdmin', 1: 'Administrator User', 2: 'Distributor User', 3: 'End User',
                }[scope.row.userType] }}</span>
              </template>
            </el-table-column>
            <el-table-column property="userLevel" label="level">
              <template #default="scope">
                <span>{{ {
                  0: 'T0', 1: 'T1', 2: 'T2', 3: 'T3', 4: 'T4', 5:
                    'T5', 6: 'T1', 7: 'T2', 8: 'T3', 9: 'T4',
                }[scope.row.userLevel] }}</span>
              </template>
            </el-table-column>
            <el-table-column property="ipaddr" label="ipaddress" />
            <el-table-column property="loginLocation" label="loginLocation" width="200"/>
            <el-table-column property="browser" label="browser" />
            <el-table-column property="os" label="os" />
            <el-table-column property="message" label="message" width="280"/>
            <el-table-column property="accessTime" label="time"/>
            <el-table-column property="operate" label="operate" width="200">
              <template #default="scope">
                <!-- <span class="more-button" @click="detailfun(scope.row)" style="cursor: pointer;">
                  detail
                </span>
                <span class="more-button" @click="edit(scope.$index, scope.row)" style="cursor: pointer;">
                  edit
                </span> -->
                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;" v-if="hasPermission('system:login:remove')">
                  delete
                </span>
              </template>

            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
            <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
              style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
          </div>
          <el-dialog v-model="dialogVisible" title="delete" width="500">
            <span>Are you sure you want to delete it</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">cancel</el-button>
                <el-button type="primary" @click="yesdel()">
                  sure
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.administrator {
  padding: 15px;
  background-color: #eff1f4;

  .administratorbas {
    background-color: #fff;
    width: 100%;
    height: 88vh;
    border-radius: 10px 10px 0 0;

    .top {
      height: 50px;
      background-color: #f9f9f9;
      border-radius: 10px 10px 0 0;
      font-size: 20px;
      font-weight: bold;
      overflow: hidden;
      border-bottom: 1px solid #f1eded;

      span {
        display: block;
        margin: 10px 0 0 15px;
      }
    }

    .cont {
      // .one {
      //     margin: 10px;
      //     display: flex;
      //     padding: 10px;

      //     div {
      //         margin-right: 20px;
      //     }
      // }
      .one {
        margin: 10px;
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        align-items: center;
        padding: 10px;
      }

      .select {
        display: flex;
        align-items: center;
      }

      .exp {
        .export-excel {
          margin-left: 20px;
        }
      }

      .tab {
        margin-top: 20px;
        width: 100%;
        position: relative;
        min-height: 300px;

        .el-table {
          --el-table-header-bg-color: #fafafa;
        }

        .el-switch {
          --el-switch-on-color: #45d585;
        }

        .more-button {
          margin-left: 8px;
          margin-top: 3px;
          /* 为“更多”按钮添加左边距 */
          color: #409EFF;
          outline: none;

          /* Element Plus 主题色 */
          &:hover {
            color: #66b1ff;

            /* 鼠标悬停时的颜色 */
          }
        }
      }
    }
  }

  /* 如果使用 scoped，需要添加 ::v-deep */
  ::v-deep .custom-modal {
    background-color: rgba(0, 0, 0, 0.5);
    /* 设置弹窗背景颜色为半透明 */
  }

  /* 或者更精确的定位 */
  ::v-deep .custom-modal .el-overlay {
    background-color: rgba(0, 0, 0, 0.8);
  }
}
</style>